<template>
  <div class="pane-account">
    <el-form :model="account" :rules="accountRules" label-width="60px" size="large" status-icon ref="formRef">
      <el-form-item label="帐号" prop="username">
        <el-input v-model="account.username">
          <template #prefix>
            <el-icon><user /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-tooltip :visible="isCapslock" content="大写锁定已打开" placement="right">
        <el-form-item label="密码" prop="password">
          <el-input v-model="account.password" show-password :prefix-icon="Lock" @keyup="checkCapslock" @keyup.enter="loginAction" />
        </el-form-item>
      </el-tooltip>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import type { FormRules, ElForm } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'

const useStore = useUserStore()
const emit = defineEmits(['loadingClick'])
// 是否大写锁定
const isCapslock = ref(false)
//获取路由器
const $router = useRouter()
//路由对象
let $route = useRoute()
// 1.定义account数据
const account = reactive<IAccount>({
  username: localCache.getCache('username') ?? 'admin',
  password: localCache.getCache('password') ?? '111111'
})
//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (!value) {
    return callback(new Error('必须输入帐号信息~'))
  } else if (!/^[a-z0-9]{5,20}$/.test(value)) {
    callback(new Error('必须是5~20数字或字母组成~'))
  } else {
    callback()
  }
}
// 2.定义校验规则
const accountRules: FormRules = {
  username: [{ required: true, validator: validatorUserName, trigger: 'blur' }],
  password: [
    { required: true, message: '必须输入密码信息~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,}$/, message: '必须是3位以上数字或字母组成', trigger: 'blur' }
  ]
}
// 3.执行帐号的登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()

//登录按钮回调
const loginAction = (isRemPwd: boolean) => {
  //保证全部表单相校验通过再发请求
  formRef.value?.validate(async (valid) => {
    if (valid) {
      //加载效果:开始加载
      emit('loadingClick', true)
      try {
        // 1.获取用户输入的帐号和密码
        const username = account.username
        const password = account.password
        // 2.向服务器发送网络请求(携带账号和密码)
        await useStore.userLogin({ username, password })
        //登录成功加载效果也消失
        emit('loadingClick', false)
        // 3.判断是否需要记住密码
        if (isRemPwd) {
          localCache.setCache('username', username)
          localCache.setCache('password', password)
        } else {
          localCache.removeCache('username')
          localCache.removeCache('password')
        }
        //编程式导航跳转到展示数据首页
        //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
        let redirect: any = $route.query.redirect
        $router.push({ path: redirect || '/' })
        //登录成功提示信息
        ElNotification({ type: 'success', message: '欢迎回来', title: `HI,${getTime()}好` })
      } catch (error) {
        //登录失败加载效果消息
        emit('loadingClick', false)
        //登录失败的提示信息
        ElNotification({ type: 'error', message: (error as Error).message })
      }
    } else {
      ElMessage.error('Oops, 请您输入正确的格式后再操作~~.')
    }
  })
}

// 检查输入大小写
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState('CapsLock')
  }
}

defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.pane-account {
  color: red;
}
</style>
